//
//  XZAddressVC.m
//  Teecloud
//
//  Created by PC on 2018/12/10.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "XZAddressVC.h"

@interface XZAddressVC ()<MYTreeTableViewControllerParentClassDelegate>
@property (nonatomic, strong) UILabel *rightLabel;
@property (nonatomic, strong) UILabel *leftLabel;
@property(nonatomic, strong)NSMutableArray *items;
@property(nonatomic, strong)NSString *name;
@property(nonatomic, strong)NSString *parentName1;
@property(nonatomic, strong)NSString *parentName2;
//省代码,地代码,县代码
@property (nonatomic, copy) NSString *fieldValue;
@end

@implementation XZAddressVC

- (instancetype)init{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"选择地区";
    self.view.backgroundColor = [UIColor colorWithHexString:@"DDDDDD" andAlpha:1.0f];
    self.classDelegate = self;
    
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 50)];
    headView.backgroundColor = kWhiteColor;
    [headView addSubview:self.rightLabel];
    [headView addSubview:self.leftLabel];
    [self.rightLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(headView).offset(15);
        make.centerY.mas_equalTo(headView);
    }];
    
    [self.leftLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(headView).offset(-15);
        make.centerY.mas_equalTo(headView);
    }];
    [self.view addSubview:headView];
}
#pragma mark - Setter
- (UILabel *)rightLabel{
    if (!_rightLabel) {
        _rightLabel = [[UILabel alloc]init];
        _rightLabel.font = [UIFont systemFontOfSize:15.0f];
        _rightLabel.textAlignment = NSTextAlignmentLeft;
        _rightLabel.adjustsFontSizeToFitWidth = YES;
        _rightLabel.textColor = kBlackColor;
        _rightLabel.backgroundColor = kWhiteColor;
    }
    return _rightLabel;
}
- (UILabel *)leftLabel{
    if (!_leftLabel) {
        _leftLabel = [[UILabel alloc]init];
        _leftLabel.font = [UIFont systemFontOfSize:15.0f];
        _leftLabel.adjustsFontSizeToFitWidth = YES;
        _leftLabel.textAlignment = NSTextAlignmentRight;
        _leftLabel.backgroundColor = kWhiteColor;
        _leftLabel.text = @"未选择";
        _leftLabel.textColor = [UIColor colorWithHexString:@"8c8c8c" andAlpha:1.0f];
    }
    return _leftLabel;
}

#pragma mark - MYTreeTableViewControllerParentClassDelegate
- (MYTreeTableManager *)managerInTableViewController:(MYTreeTableViewController *)tableViewController {
    
    // 获取数据并创建树形结构
    NSData *JSONData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"regions" ofType:@"json"]];
    NSArray *provinceArray = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingAllowFragments error:nil];
    
    self.items = [NSMutableArray array];
    
    // 1. 遍历省份
    [provinceArray enumerateObjectsUsingBlock:^(NSDictionary *province, NSUInteger idx, BOOL * _Nonnull stop) {
        
        MYTreeItem *provinceItem = [[MYTreeItem alloc] initWithName:province[@"Name"]
                                                                 id:@([province[@"Code"] integerValue])
                                                           parentId:nil
                                                            orderNo:@(idx)
                                                               type:@"province"
                                                             isLeaf:NO
                                                               data:province];
        [self.items addObject:provinceItem];
        
        // 2. 遍历城市
        NSArray *cityArray = province[@"Next"];
        [cityArray enumerateObjectsUsingBlock:^(NSDictionary *city, NSUInteger idx, BOOL * _Nonnull stop) {
            
            MYTreeItem *cityItem = [[MYTreeItem alloc] initWithName:city[@"Name"]
                                                                 id:@([city[@"Code"] integerValue])
                                                           parentId:provinceItem.id
                                                            orderNo:@(idx)
                                                               type:@"city"
                                                             isLeaf:NO
                                                               data:city];
            [self.items addObject:cityItem];
            
            // 3. 遍历区
            NSArray *districtArray = city[@"Next"];
            [districtArray enumerateObjectsUsingBlock:^(NSDictionary *district, NSUInteger idx, BOOL * _Nonnull stop) {
                
                MYTreeItem *districtItem = [[MYTreeItem alloc] initWithName:district[@"Name"]
                                                                         id:@([district[@"Code"] integerValue])
                                                                   parentId:cityItem.id
                                                                    orderNo:@(idx)
                                                                       type:@"district"
                                                                     isLeaf:YES
                                                                       data:district];
                [self.items addObject:districtItem];
            }];
        }];
    }];
    
    // ExpandLevel 为 0 全部折叠，为 1 展开一级，以此类推，为 NSIntegerMax 全部展开
    MYTreeTableManager *manager = [[MYTreeTableManager alloc] initWithItems:self.items andExpandLevel:NSIntegerMin];
    
    return manager;
}

- (void)tableViewController:(MYTreeTableViewController *)tableViewController checkItems:(NSArray<MYTreeItem *> *)items {
    
    // 这里加一个隔离带目的是可以在这里做出个性化操作，然后再将数据传出
    if ([self.delegate respondsToSelector:@selector(tableViewController:checkItems:)]) {
        [self.delegate tableViewController:self checkItems:items];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)searchBarShouldBeginEditingInTableViewController:(MYTreeTableViewController *)tableViewController {
    
    NSLog(@"点击了搜索栏");
}

- (void)tableViewController:(MYTreeTableViewController *)tableViewController didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSArray *arr = [self getShowItems];
    MYTreeItem *item = arr[indexPath.row];
    if (item.level == 0) {
        self.name = [NSString stringWithFormat:@"%@", item.name];
    } else if (item.level == 1) {
        self.name = [NSString stringWithFormat:@"%@%@", item.parentItem.name, item.name];
    } else {
        self.name = [NSString stringWithFormat:@"%@%@%@", item.parentItem.parentItem.name, item.parentItem.name, item.name];
        self.fieldValue = [NSString stringWithFormat:@"%@,%@,%@",item.parentItem.parentItem.id, item.parentItem.id, item.id];
        //未登录 完善信息
        if ([self.type isEqualToString:@"UNSCUCESS"]) {
            [self updateAddreess:@"Region" fieldValue:self.fieldValue];
        }else{
           [self updateUserInfo:@"Region" fieldValue:self.fieldValue];
        }
        
    }
    self.rightLabel.text = self.name;
    self.leftLabel.textColor = kBlackColor;
    self.leftLabel.text = @"已选地区";
    [self.tableView reloadData];
}

- (void)tableViewController:(MYTreeTableViewController *)tableViewController didSelectCheckBoxRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"点击了第 %ld 行的 checkbox", (long)indexPath.row);
    [self getShowItems];
}
//更新用户信息
- (void)updateUserInfo:(NSString *)fieldName fieldValue:(NSString *)fieldValue{
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                           @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"newUserId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"fieldName":fieldName,
                          @"fieldValue":fieldValue
                          };
    
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=UpdateUserInfo&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                [weakself.navigationController popViewControllerAnimated:true];
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
            
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
    
}
/**
 更新用户信息 30.5
 
 @param fieldName 数据名称
 @param fieldValue 数据值
 */
- (void)updateAddreess:(NSString *)fieldName fieldValue:(NSString *)fieldValue{
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"newUserId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"fieldName":fieldName,
                          @"fieldValue":fieldValue
                          };
    
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"/do-api.ashx?$m=UpdateUserInfo&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                [weakself.navigationController popViewControllerAnimated:true];
                if (weakself.AddressBlock) {
                    weakself.AddressBlock(weakself.name);
                }
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
    
}
@end
